#coding=utf-8
import struct
import ctypes
import time
import serial
import serial.tools.list_ports

import glob


# port=glob.glob('*')
# print("port=",port)
# McuSerialName ='COM87'
# SerialName = McuSerialName
# baudrate = 230400
# tt_timeout = 1
# plist = list(serial.tools.list_ports.comports())
# serialFd = serial.Serial(McuSerialName, baudrate, timeout=tt_timeout)
# print("serialFd=",serialFd)

# def Rece_command():
# 	fw_reply = []
# 	buf_ack = []
# 	serialFd.flush()
# 	for i in range(7):
# 		buf_ack.append(serialFd.readline())
# 		if buf_ack[i][-2:] == '\r\n':
# 			fw_reply.append(buf_ack[i])
# 			print("fw_reply=",fw_reply)
# 		if (buf_ack[i][-14:]=='fixture_done\r\n' or buf_ack[i][-6:]=='done\r\n' ):
# 			break
# 	if(fw_reply[:8]=='aabbccdd'):
# 		serialFd.reset_input_buffer()
# 		serialFd.reset_output_buffer()
# 		lb1_str="aabbccdd=989898"
# 		lb1_str = lb1_str + "\r\n"
# 		serialFd.write(lb1_str.encode('utf-8'))
# 		print("buf_ack=",buf_ack)
# 		print("lb1_str=",lb1_str)



class ChannelConfig(ctypes.Structure):
	_fields_ = [("ClockRate",   ctypes.c_int),
				("LatencyTimer",ctypes.c_ubyte),
				("Options",     ctypes.c_int)]

class I2C_TRANSFER_OPTION(object):
	START_BIT           = 0x01
	STOP_BIT            = 0x02
	BREAK_ON_NACK       = 0x04
	NACK_LAST_BYTE      = 0x08
	FAST_TRANSFER_BYTES = 0x10
	FAST_TRANSFER_BITS  = 0x20
	FAST_TRANSFER       = 0x30
	NO_ADDRESS          = 0x40

# convert list to C type str
def P2C_data(py_data):
	raw = struct.pack("%dB" % len(py_data), *py_data)
	return ctypes.create_string_buffer(raw, len(py_data))

class FT_DEVICE_LIST_INFO_NODE(ctypes.Structure):
	_fields_ = [("Flags", ctypes.c_int),
	("Type",ctypes.c_int),
	("ID", ctypes.c_int),
	("LocId",ctypes.c_int),
	("SerialNumber",ctypes.c_char*16),
	("Description",ctypes.c_char*64)]



# libMPSSE  = ctypes.cdll.LoadLibrary(r"\\Mac\Home\Desktop\desktopfiles\pywenjian\test\test_eg_20220325\i2c\libMPSSE.dll")
libMPSSE  = ctypes.cdll.LoadLibrary(r"./libMPSSE.dylib")
mode      = I2C_TRANSFER_OPTION.START_BIT|I2C_TRANSFER_OPTION.STOP_BIT
# mode    = I2C_TRANSFER_OPTION.START_BIT|I2C_TRANSFER_OPTION.STOP_BIT|I2C_TRANSFER_OPTION.BREAK_ON_NACK
# mode = 0x00



libMPSSE.Init_libMPSSE()

#获取连接主机的I2C通道数量#
chn_count   = ctypes.c_int()
ret = libMPSSE.I2C_GetNumChannels(ctypes.byref(chn_count))
print("status:",ret,"number of channels:",chn_count.value)

#获取I2C通道详细信息#
info = FT_DEVICE_LIST_INFO_NODE()
# libMPSSE.FT_DEVICE_LIST_INFO_NODE(info)
for i in range(chn_count.value):
	ret = libMPSSE.I2C_GetChannelInfo(i,ctypes.byref(info))
	print("status:",ret)
	print("Flags:",info.Flags)
	print("Type:",info.Type)
	print("ID:",info.ID)
	print("LocId:",info.LocId)
	print("SerialNumber:",info.SerialNumber)
	print("Description:",info.Description)


#打开I2C通道#
handle  = ctypes.c_void_p()
chn_no  = 0 #
ret = libMPSSE.I2C_OpenChannel(chn_no, ctypes.byref(handle))
print("I2C_OpenChannel status:",ret,"handle:",handle)

#初始化I2C通道，配置I2C通道#
class ChannelConfig(ctypes.Structure):
	_fields_ = [("ClockRate",   ctypes.c_int),
				("LatencyTimer",ctypes.c_ubyte),
				("Options",     ctypes.c_int)]

chn_conf            = ChannelConfig(1000,1,0)
ret = libMPSSE.I2C_InitChannel(handle,ctypes.byref(chn_conf))
print("I2C_InitChannel status:",ret)

#I2C通道写入数据#
I2Caddress          = 0b0100000
values              = [0x06, 0x00,0x00]
raw                 = struct.pack("%dB" % len(values),*values)
wrt_buf = ctypes.create_string_buffer(raw,len(raw))
bytes_transfered    = ctypes.c_int()
libMPSSE.I2C_DeviceWrite(handle, I2Caddress, len(wrt_buf), wrt_buf, ctypes.byref(bytes_transfered), mode)
values              = [0x04, 0x00,0x00]
raw                 = struct.pack("%dB" % len(values),*values)
wrt_buf = ctypes.create_string_buffer(raw,len(raw))
bytes_transfered    = ctypes.c_int()
libMPSSE.I2C_DeviceWrite(handle, I2Caddress, len(wrt_buf), wrt_buf, ctypes.byref(bytes_transfered), mode)
#
values              = [0x07, 0x00,0x00]
raw                 = struct.pack("%dB" % len(values),*values)
wrt_buf = ctypes.create_string_buffer(raw,len(raw))
bytes_transfered    = ctypes.c_int()
libMPSSE.I2C_DeviceWrite(handle, I2Caddress, len(wrt_buf), wrt_buf, ctypes.byref(bytes_transfered), mode)
values              = [0x05, 0x00,0x00]
raw                 = struct.pack("%dB" % len(values),*values)
wrt_buf = ctypes.create_string_buffer(raw,len(raw))
bytes_transfered    = ctypes.c_int()
libMPSSE.I2C_DeviceWrite(handle, I2Caddress, len(wrt_buf), wrt_buf, ctypes.byref(bytes_transfered), mode)



#I2C通道写入数据#
I2Caddress          = 0b0100000
values              = [0x02,0x00,0x40]
raw                 = struct.pack("%dB" % len(values),*values)
wrt_buf = ctypes.create_string_buffer(raw,len(raw))
bytes_transfered    = ctypes.c_int()

ret = libMPSSE.I2C_DeviceWrite(handle, I2Caddress, len(wrt_buf), wrt_buf, ctypes.byref(bytes_transfered), mode)
print("I2C_DeviceWrite status: {}, {} bytes transfered, the data is {}".format(ret, bytes_transfered.value, wrt_buf.value))

# I2Caddress          = 0b0100000
# values              = [0x03,0xff]
# raw                 = struct.pack("%dB" % len(values),*values)
# wrt_buf = ctypes.create_string_buffer(raw,len(raw))
# bytes_transfered    = ctypes.c_int()
#
# ret = libMPSSE.I2C_DeviceWrite(handle, I2Caddress, len(wrt_buf), wrt_buf, ctypes.byref(bytes_transfered), mode)
# print("I2C_DeviceWrite status: {}, {} bytes transfered, the data is {}".format(ret, bytes_transfered.value, wrt_buf.value))

#I2C通道读取数据#
I2Caddress          = 0b0100000
values_r              = [0x00, 0x00]
raw_r                 = struct.pack("%dB" % len(values_r),*values_r)
rd_buf = ctypes.create_string_buffer(raw_r,len(raw_r))
bytes_transfered    = ctypes.c_int()

ret = libMPSSE.I2C_DeviceRead(handle, I2Caddress, len(rd_buf), rd_buf, ctypes.byref(bytes_transfered), mode)
print("I2C_DeviceRead status: {}, {} bytes transfered, the data is {}".format(ret, bytes_transfered.value, rd_buf.value))

#关闭I2C通道#
ret = libMPSSE.I2C_CloseChannel(handle)
print("I2C_CloseChannel status:",ret)

#清理I2C通道
libMPSSE.Cleanup_libMPSSE()

# def calStart():
#     for i in range (500):
#         Rece_command()
#         time.sleep(0.5)

# calStart()


#GPIO 功能不适合FT4232，只适合带有ACBUS的器件#
# Chndir = P2C_data([0xff])
# LED_On = P2C_data([0xff])
# LED_Off = P2C_data([0x00])

# ret = libMPSSE.I2C_OpenChannel(0, ctypes.byref(handle))
# ret = libMPSSE.I2C_InitChannel(handle,ctypes.byref(chn_conf))
# ret = libMPSSE.FT_WriteGPIO(handle, Chndir, LED_Off)
# while 1:
#     time.sleep(0.1)
#     ret = libMPSSE.FT_WriteGPIO(handle, Chndir, LED_On)
#     time.sleep(0.1)
#     ret = libMPSSE.FT_WriteGPIO(handle, Chndir, LED_Off)
#     time.sleep(0.1)
